import axios from "axios";
import qs from "qs";
import Global from "@/libs/Global.js";
import {getToken} from "@/libs/util.js";

const userInfo = Global.getUserInfo();
//配置axios
axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
axios.defaults.timeout = 20000;

const ajax = axios.create({
    timeout: 20000,
    headers: { 
        "Content-Type": "application/x-www-form-urlencoded" ,
        "BzAdminToken" : getToken(),
        "BzAdminuserId" : userInfo.admin_user_id,
        "BzRedisKey" : userInfo.redis_key
    },
    withCredentials: true
});

ajax.interceptors.request.use(
    req => {
        req.data = qs.stringify(req.data);
        Global.loading = true;
        return req;
    },
    function(err) {
        Global.loading = false;
        return Promise.reject(error);
    }
);

ajax.interceptors.response.use(
    function(response) {
        return response;
    },
    function(error) {
        if (error.response.status == 401) {
            //当前登录失效
            alert("登陆失效："+error.response.data.msg);
            window.location.href = "/logout";
        } else if (error.response.status == 403) {
            //当前操作没有权限
            alert("您没有权限进行当前操作："+error.response.data.msg);
        } else {
            alert("系统异常:"+error.response.data.msg);
        }
        return Promise.reject(error);
    }
);

export default ajax;
